package com.example.httpdemo


import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.httpdemo.entity.*
import com.example.httpdemo.front.*
import com.example.httpdemo.retrofit.RetrofitUtil
import com.example.httpdemo.retrofit.service.ElectricService
import com.example.httpdemo.retrofit.service.LibraryService
import com.example.httpdemo.retrofit.service.StudentService
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sendRequestBtn.setOnClickListener {
//            getQuaDeve("18251104126")
//            getElectricOne("97", "519")
//            getRecommendBook()
//            getSearchList("追风筝的人")

//            val getStuInfo = GetStuInfo("账号", "密码")
//            getStudentInfo(getStuInfo)

//            val getGradeInfo = GetGradeInfo("账号", "密码", "2019-2020-1")
//            getStudentGrade(getGradeInfo)

//            val getCourseInfo = GetCourseInfo("账号", "密码", "2019-2020-1")
//            getStudentCourse(getCourseInfo)

//            val getGetHaveStudiedInfo = GetHaveStudiedInfo("账号", "密码")
//            getStudentHaveStudied(getGetHaveStudiedInfo)
        }
    }

    /**
     * @author :WaiterXiaoYY
     * @description: 以下是利用Retrofit进行网络请求返回数据操作方法
     * @data :2020/12/20 10:29
     */

    // 获取当前图书馆热门推荐
    private fun getRecommendBook() {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val libraryService = retrofit.create(LibraryService::class.java)

            libraryService.getRecommendBook()
                .enqueue(object : Callback<ResponseData<RecommendBook>> {

                    override fun onResponse(
                        call: Call<ResponseData<RecommendBook>>,
                        response: Response<ResponseData<RecommendBook>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中的data，列表形式，可以对数据进行数据库插入
                                val recommendBookList = responseData.data

                                // 此处调用其他方法进行操作
//                                if (recommendBookList != null) {
//                                    show(recommendBookList)
//                                }
                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<RecommendBook>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 搜索图书 query 搜索的关键词
    private fun getSearchList(query: String) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val libraryService = retrofit.create(LibraryService::class.java)

            libraryService.getSearchList(query)
                .enqueue(object : Callback<ResponseData<BookSearch>> {

                    override fun onResponse(
                        call: Call<ResponseData<BookSearch>>,
                        response: Response<ResponseData<BookSearch>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中的data，列表形式，可以对数据进行数据库插入
                                val bookSearchList = responseData.data

                                // 此处调用其他方法进行操作
//                                if (bookSearchList != null) {
//                                    show(bookSearchList)
//                                }
                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<BookSearch>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 获取学生信息 传入一个对象，需包含教务系统的学号和密码，一般在首次登陆的时候进行（或单独刷新个人资料）
    private fun getStudentInfo(getStuInfo: GetStuInfo) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val studentService = retrofit.create(StudentService::class.java)

            studentService.getStudentInfo(getStuInfo)
                .enqueue(object : Callback<ResponseData<StudentInfo>> {

                    override fun onResponse(
                        call: Call<ResponseData<StudentInfo>>,
                        response: Response<ResponseData<StudentInfo>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中的data，列表形式，可以对数据进行数据库插入
                                val studentInfoList = responseData.data

                                // 此处调用其他方法进行操作
                                if (studentInfoList != null) {
                                    show(studentInfoList)
                                }
                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<StudentInfo>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 获取学生成绩 传入一个对象，需包含教务系统的学号、密码和查询学期（termTime) tremTime为"" 则查询全部，具体如2019-2020-2
    private fun getStudentGrade(getGradeInfo: GetGradeInfo) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val studentService = retrofit.create(StudentService::class.java)

            studentService.getStudentGrade(getGradeInfo)
                .enqueue(object : Callback<ResponseGradeData> {

                    override fun onResponse(
                        call: Call<ResponseGradeData>,
                        response: Response<ResponseGradeData>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中数据，列表形式，可以对数据进行数据库插入
                                val explainList = responseData.explain // 修读基本信息
                                val gradeList = responseData.grade //查询范围的各课程情况
                                val gpaList = responseData.gpa // 查询范围的绩点
                                // 此处调用其他方法进行操作

                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseGradeData>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 获取学生课程 传入一个对象，需包含教务系统的学号、密码和查询学期（termTime) 不支持查询全部，具体如2019-2020-2
    private fun getStudentCourse(getCourseInfo: GetCourseInfo) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val studentService = retrofit.create(StudentService::class.java)

            studentService.getStudentCourse(getCourseInfo)
                .enqueue(object : Callback<ResponseData<Course>> {

                    override fun onResponse(
                        call: Call<ResponseData<Course>>,
                        response: Response<ResponseData<Course>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中数据，列表形式，可以对数据进行数据库插入
                                val courseList = responseData.data // 修读基本信息

                                // 此处调用其他方法进行操作

                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<Course>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 获取已修各模块的课程学分情况 传入一个对象，需包含教务系统的学号、密码
    private fun getStudentHaveStudied(getHaveStudiedInfo: GetHaveStudiedInfo) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val studentService = retrofit.create(StudentService::class.java)

            studentService.getStudentHaveStudied(getHaveStudiedInfo)
                .enqueue(object : Callback<ResponseData<HaveStudied>> {

                    override fun onResponse(
                        call: Call<ResponseData<HaveStudied>>,
                        response: Response<ResponseData<HaveStudied>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中数据，列表形式，可以对数据进行数据库插入
                                val haveStudiedList = responseData.data // 修读基本信息

                                // 此处调用其他方法进行操作

                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<HaveStudied>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 获取素质拓展修读情况 传入学号
    private fun getQuaDeve(studentId: String) {
        try {
            val retrofitUtil = RetrofitUtil()
            val retrofit = retrofitUtil.getRetrofitUtil()
            val studentService = retrofit.create(StudentService::class.java)

            studentService.getStuQuaDeve(studentId)
                .enqueue(object : Callback<ResponseData<QuaDeveInfo>> {

                    override fun onResponse(
                        call: Call<ResponseData<QuaDeveInfo>>,
                        response: Response<ResponseData<QuaDeveInfo>>
                    ) {
                        val responseData = response.body()
                        if (responseData != null) {
                            if (responseData.code == 200) {
                                // 取到返回值中的data，列表形式，可以对数据进行数据库插入
                                val quaDeveInfoList = responseData.data

                                // 此处调用其他方法进行操作
//                                if (quaDeveInfoList != null) {
////                                    show(quaDeveInfoList)
////                                }
                            }
                        }
                    }

                    override fun onFailure(
                        call: Call<ResponseData<QuaDeveInfo>>,
                        t: Throwable
                    ) {
                        t.printStackTrace()
                    }

                })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    // 获取电控信息，传入buildingId和roomName
    private fun getElectricOne(buildingId: String, roomName: String) {
        thread {
            try {
                val retrofitUtil = RetrofitUtil()
                val retrofit = retrofitUtil.getRetrofitUtil()

                val electricService = retrofit.create(ElectricService::class.java)
                val getElectricOneInfo = GetElectricOneInfo(buildingId, roomName)

                electricService.getElctricOne(getElectricOneInfo)
                    .enqueue(object : Callback<ResponseData<Electric>> {
                        override fun onResponse(
                            call: Call<ResponseData<Electric>>,
                            response: Response<ResponseData<Electric>>
                        ) {
                            val responseData = response.body()
                            if (responseData != null) {
                                if (responseData.code == 200) {
                                    // 取到返回值中的data，列表形式，可以对数据进行数据库插入
                                    val electricList = responseData.data

                                    // 此处调用其他方法进行操作
//                                    if (electricList != null) {
//                                        show(electricList)
//                                    }
                                }
                            }
                        }

                        override fun onFailure(call: Call<ResponseData<Electric>>, t: Throwable) {
                            t.printStackTrace()
                        }
                    })


            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun show(lists : List<StudentInfo>) {
        for(list in lists) {
            Log.d("MainActivity", "${list}")
        }
    }

    /**
     * @author :WaiterXiaoYY
     * @description: 以下是okhttp的用法，可忽略
     * @data :2020/12/20 10:29
     */


    private fun okkHttpUtil() {
        //                val client = OkHttpClient()
//                val requestBody = FormBody.Builder()
//                    .add("buildingId", "97")
//                    .add("roomName", "519")
//                    .build()
//                val stringBody ="{'buildingId': '97', 'roomName': '519',}".toRequestBody("application/json;charset=utf-8".toMediaType())
//                val request:Request=Request
//                    .Builder()
//                    .url("http://172.27.184.11:9092/api/getelctricone")
//                    .post(requestBody)
//                    .build()
//                val request = Request.Builder()
//                    .url("http://172.27.184.11:9092/api/searchbook/" + "追风筝的人")
//                    .build()
//                val response = client.newCall(request).execute()
//                val responseData = response.body?.string()
//                if (responseData != null) {
//                    Log.d("MainActivity", responseData)
//                    parseJSONWithGSON(responseData)
//                }
    }

    private fun parseJSONWithGSON(jsonData: String) {
        val gson = Gson()
        val typeOf = object : TypeToken<ResponseData<BookSearch>>() {}.type
        val reData = gson.fromJson<ResponseData<BookSearch>>(jsonData, typeOf)
        for (bookSearch in reData.data!!) {
            Log.d("MainActivity", "${bookSearch}")
        }
//        val typeOf = object : TypeToken<ResponseData<Electric>>(){}.type
//        val reData = gson.fromJson<ResponseData<Electric>>(jsonData, typeOf)
//        for(electric in reData.data!!) {
//            Log.d("MainActivity", "${electric}")
//        }
//        Log.d("MainActivity", "${reData.data}")
//        Log.d("MainActivity", "${reData.msg}")
//        Log.d("MainActivity", "${reData.code}")
    }

    private fun showResponse(response: String) {
        runOnUiThread {
            responseText.text = response
        }
    }

    private fun formatJson(content: String): String {
        val gson = GsonBuilder().setPrettyPrinting().create()
        val jsonParser = JsonParser()
        val jsonElement = jsonParser.parse(content)
        return gson.toJson(jsonElement)
    }
}


